from django.utils import timezone

from app.models import PowerData, BMSInformation
from app.models.pcs_system import PowerSystem


def updatePowerGridData(powerData):
    print("enter data to database")
    originData = PowerData.objects.filter(sn_id=powerData.sn_id)
    print(originData)
    if originData.exists():
        print("update data to database")
        originData.delete()
        # powerData.sn_id = powerData.sn_id
        powerData.update_time = timezone.now()
        powerData.save()
    else:
        print("insert data to database")
        db_data = PowerData(sn_id=powerData.sn_id,
                            grid_voltage=powerData.grid_voltage,
                            grid_voltage_harmonic_distortion=powerData.grid_voltage_harmonic_distortion,
                            grid_frequency=powerData.grid_frequency,
                            output_voltage=powerData.output_voltage,
                            grid_current=powerData.grid_current,
                            grid_active_power=powerData.grid_active_power,
                            grid_reactive_power=powerData.grid_reactive_power,
                            grid_apparent_power=powerData.grid_apparent_power,
                            grid_power_factor=powerData.grid_power_factor,
                            ups_voltage=powerData.ups_voltage,
                            ups_current=powerData.ups_current,
                            ups_frequency=powerData.ups_frequency,
                            ups_active_power=powerData.ups_active_power,
                            ups_reactive_power=powerData.ups_reactive_power,
                            ups_apparent_power=powerData.ups_apparent_power,
                            ups_power_factor=powerData.ups_power_factor,
                            bus_voltage=powerData.bus_voltage,
                            create_time=powerData.create_time)
        db_data.save()


def updateBmsData(bmsData):
    print("enter bmsdata to database")
    originData = BMSInformation.objects.filter(sn_id=bmsData.sn_id).first()
    # print(originData)
    if originData:
        print("update bmsdata to database")
        originData.sn_id = bmsData.sn_id
        originData.update_time = timezone.now()
        print(timezone.now())
        originData.save()
    else:
        print("insert data to database")
        bmsData.save()


def updateSystemData(systemData):
    originData = PowerSystem.objects.filter(sn_id=systemData.sn_id).first()
    if originData:
        print("update bmsdata to database")
        originData.sn_id = systemData.sn_id
        originData.update_time = timezone.now()
        print(timezone.now())
        originData.save()
    else:
        print("insert data to database")
        systemData.save()
